package org.future.loader;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

/**
 *@date   2010-3-27 下午08:34:20
 *@author dycc
 *@file   org.future.StreamClassLoader.java
 */
public class StreamClassLoader extends ClassLoader{
	// 当前类的一个实例
	private static StreamClassLoader instance;
	/**
	 * 构造方法设为私有的
	 */
	private StreamClassLoader(){
	}
	/**
	 * 返回当前类的一个实例
	 * @return
	 */
	public static StreamClassLoader getInstance(){
		if(instance == null){
			instance = new StreamClassLoader();
		}
		return instance;
	}
	/**
	 * 从文件中加载一个类
	 * @param filePath   例: D:/temp/classes/AppleTree.class
	 * @param className  例: org.future.locale.AppleTree
	 * @return  The Class object that was created from the specified file.
	 */
	@SuppressWarnings(value="unchecked")
	public Class load(String filePath,String className)
		throws FileNotFoundException,IOException{
		FileInputStream in = new FileInputStream(filePath);
		return load(in,className);
	}
	
	/**
	 * 从流中加载一个类
	 * @param in
	 * @param className  例: org.future.locale.AppleTree
	 * @return  The Class object that was created from the specified inputStream.
	 */
	@SuppressWarnings(value="unchecked")
	public Class load(InputStream in,String className)throws IOException{
		// 如果该类已经被加载过则直接返回
		Class cls =  this.findLoadedClass(className);
		if(cls != null){
			return cls;
		}
		// 从流中读取所有的字节
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = -1;
		while((len = in.read(data, 0, data.length)) > 0){
			out.write(data, 0, len);
		}
		data = out.toByteArray();
		in.close();
		out.close();
		// 调用父类方法从字节数组中加载类
		return defineClass(className, data, 0, data.length);
	}
}
